import { createRouter, createWebHistory } from 'vue-router'
import store from '../store/store';
import axios from 'axios';
// 创建模式
const routerHistory = createWebHistory()
// 创建router
const router = createRouter({
  history: routerHistory,
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/Home.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
      meta: { redirectAlreadyLogin: true}
    },
    {
      path: '/column/:id',
      name: 'column',
      component: () => import('../views/ColumnDetail.vue')
    },
    {
      path: '/create',
      name: 'create',
      component: () => import('../views/CreatePost.vue'),
      meta: { requiredLogin: true}
    },
    {
      path: '/signup',
      name: 'signup',
      component: () => import('../views/Signup.vue'),
      meta: { redirectAlreadyLogin: true}
    },
    {
      path: '/postdetail/:column/:id',
      name: 'postDetail',
      component: () => import('../views/PostDetail.vue')
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 }
  }
})
// 导航守卫 to 要去的路由， from 从哪里来的路由  next 放行函数
router.beforeEach( (to, from , next) => {
  // console.log(store.getters.isLogin);
  // 如果登陆了
  if (store.state.user.isLogin){
    // 如果访问登陆不能访问的路由返回 home
    if (to.meta.redirectAlreadyLogin) {
      next({name: 'home'})
      // 如果不需要则放行
    } else {
      next()
    }
  // 如果没登录
  } else {
    
    const token = localStorage.getItem('toKen')
    // 如果有token
    if (token) {
      
      // 发送请求
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
  
      
      // 发送成功回调
      store.dispatch('getInfo').then(() => {
        // 判断登录后是不是不能访问
        if (to.meta.redirectAlreadyLogin) {
          next({name: 'home'})
          // 不是则放行
        }else {
          next()
        }
        // 失败回调
      }).catch(() => {
        store.commit('OUTLOGIN')
        next({name: 'login'})
      })
    } else {
      if (to.meta.requiredLogin) {
        next({name: 'login'})
      } else {
        next()
      }
    }
  }
  
})
export default router